<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="申请工区" prop="gqName">
        <el-input size="mini"
                  v-model="queryParams.gqName"
                  placeholder="请输入申请工区"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="sqName">
        <el-input size="mini"
                  v-model="queryParams.sqName"
                  placeholder="请输入申请人"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间">
        <el-date-picker size="mini"
                        v-model="daterangeSqTime"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="流程状态" prop="processStatus">
        <el-select v-model="queryParams.processStatus" placeholder="请选择流程状态" clearable size="mini">
          <el-option
            v-for="dict in dict.type.process_business_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wzgl:wzsq:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="wzsqList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="申请工区" align="center" prop="gqName" width="120"/>
      <el-table-column label="申请人" align="center" prop="sqName" width="120"/>
      <el-table-column label="申请时间" align="center" prop="sqTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sqTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="bz"/>
      <el-table-column label="申请单详情" align="center" width="120">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleSqXqClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="processStatus" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.process_business_status" :value="scope.row.processStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleJinDu(scope.row)"
            v-if="scope.row.processStatus !== 1"
          >查询进度
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-containers" v-show="total > 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改物资申请对话框 -->
    <vxe-modal :title="title" v-model="open" width="60%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">物资申请基本信息</span>
          </div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="申请工区" prop="gqName">
                <!--                <el-input v-model="form.gqName" placeholder="请输入申请工区"/>-->
                <el-select filterable v-model="form.gqName" placeholder="请选择工区" style="width: 100%">
                  <el-option
                    v-for="item in gqList"
                    :key="item.gqglId"
                    :label="item.gqName"
                    :value="item.gqName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人" prop="sqName">
                <el-input v-model="form.sqName" placeholder="请输入申请人"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注" prop="bz">
            <el-input v-model="form.bz" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-card>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">物资申请明细信息</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWzsqSqmx">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWzsqSqmx">移除</el-button>
            </el-col>
          </el-row>
          <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                    height="45vh" :data="wzsqSqmxList" :row-class-name="rowWzsqSqmxIndex"
                    @selection-change="handleWzsqSqmxSelectionChange" ref="wzsqSqmx">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column align="center" v-if="1 === 2" label="物资ID" prop="wzxxId" width="150"/>
            <el-table-column align="center" label="物资名称" prop="wzName" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.wzName" placeholder="请输入物资名称"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="物资单位" prop="wzDw" width="85">
              <template slot-scope="scope">
                <el-input v-model="scope.row.wzDw" placeholder="请输入物资单位"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="物资规格" prop="wzGg" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.wzGg" placeholder="请输入物资规格"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="申请数量" prop="sqSl" width="150">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.sqSl" placeholder="请输入申请数量"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="用途" prop="purpose">
              <template slot-scope="scope">
                <el-input v-model="scope.row.purpose" placeholder="请输入用途"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 物资多选 -->
    <WzDuoX ref="wzDuoX"/>

    <!-- 查询进度 -->
    <Jindu ref="picture"/>

    <!-- 物资申请单详情 -->
    <WzSqXq ref="wzSqXq"/>

  </div>
</template>

<script>
import {addWzsq, delWzsq, getWzsq, listWzsq, updateWzsq} from "@/api/wzgl/wzsq";
import WzDuoX from "@/views/components/WzDuoX/index.vue";
import {selectByQxGq} from "@/api/wzgl/gqgl";
import Jindu from "@/views/components/liuChengState/jindu.vue";
import {revokeProcess, startTask} from "@/api/activiti/task";
import WzSqXq from "@/views/wzgl/wzsq/components/WzSqXq.vue";

export default {
  name: "Wzsq",
  components: {WzSqXq, Jindu, WzDuoX},
  dicts: ['process_business_status'],
  provide() {
    return {
      updateWzLabel: (val) => {
        val.forEach(item => {
          // 检查是否已存在相同的 出厂编号
          const exists = this.wzsqSqmxList.some(existingItem => existingItem.wzxxId === item.wzxxId);
          if (!exists) {
            this.wzsqSqmxList.push(item);
          }
        })
      },
    };
  },
  data() {
    return {
      gqList: [], //后端获取到的工区列表(数据权限校验)
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWzsqSqmx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资申请表格数据
      wzsqList: [],
      // 物资申请明细表格数据
      wzsqSqmxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用途时间范围
      daterangeSqTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gqName: null,
        sqName: null,
        sqTime: null,
        bz: null,
        userId: null,
        deptId: null,
        processStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gqName: [{required: true, message: "申请工区不能为空", trigger: "blur"}],
        sqName: [{required: true, message: "申请人不能为空", trigger: "blur"}],
      },
    };
  },
  created() {
    this.getList();

    selectByQxGq().then(res => {
      this.gqList = res.data
    })
  },
  methods: {
    //打开物资申请详情
    handleSqXqClick(row) {
      this.$refs.wzSqXq.handleOpen(row)
    },
    //发起任务
    handleStartTask() {
      // 打开遮罩层
      this.$modal.loading("正在提交申请，请稍后...");
      const row = this.selectedRow; // 获取当前选中的行
      if (!row) {
        this.$message.error("请先选择一行数据");
        return;
      }
      this.$confirm("是否确认发起申请？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          startTask({businessKey: row.wzsqId, businessType: 13}).then(res => {
            this.getList();
            this.$modal.msgSuccess("发起成功");
            // 关闭遮罩层
            this.$modal.closeLoading();
            this.selectedRow = null
          });
        })
        .catch(() => {
        });
    },
    //撤销流程
    handleRevokeProcess() {
      // 打开遮罩层
      this.$modal.loading("正在撤销流程，请稍后...");
      const row = this.selectedRow; // 获取当前选中的行
      if (!row) {
        this.$message.error("请先选择一行数据");
        return;
      }
      this.$confirm("是否确撤销申请？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let params = {
            businessKey: row.wzsqId,
            businessType: 13,
            processInstanceId: row.processInstanceId
          };
          revokeProcess(params).then(res => {
            this.getList();
            this.$modal.msgSuccess("撤销成功");
            // 关闭遮罩层
            this.$modal.closeLoading();
            this.selectedRow = null
          });
        })
        .catch(() => {
        });
    },
    //查询进度
    handleJinDu(row) {
      this.$refs.picture.handleOpen(row);
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询物资申请列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeSqTime && '' != this.daterangeSqTime) {
        this.queryParams.params["beginSqTime"] = this.daterangeSqTime[0];
        this.queryParams.params["endSqTime"] = this.daterangeSqTime[1];
      }
      listWzsq(this.queryParams).then(response => {
        this.wzsqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        wzsqId: null,
        gqName: null,
        sqName: null,
        sqTime: null,
        bz: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.wzsqSqmxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSqTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wzsqId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.sqName = this.$store.state.user.name
      this.open = true;
      this.title = "添加物资申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const wzsqId = row.wzsqId || this.ids
      getWzsq(wzsqId).then(response => {
        this.form = response.data;
        this.wzsqSqmxList = response.data.wzsqSqmxList;
        this.open = true;
        this.title = "修改物资申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.wzsqSqmxList = this.wzsqSqmxList;

          if (this.form.wzsqSqmxList.length == 0) {
            this.$modal.msgError("物资申请明细不能为空");
            return
          }
          for (let i = 0; i < this.form.wzsqSqmxList.length; i++) {
            let item = this.form.wzsqSqmxList[i]
            if (item.sqSl == undefined || item.sqSl == null || item.sqSl == '') {
              this.$modal.msgError("第" + (i + 1) + "行，申请数量为空，请检查");
              return
            }
          }

          if (this.form.wzsqId != null) {
            updateWzsq(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWzsq(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wzsqIds = row.wzsqId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delWzsq(wzsqIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 物资申请明细序号 */
    rowWzsqSqmxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 物资申请明细添加按钮操作 */
    handleAddWzsqSqmx() {
      // this.$refs.wzDuoX.handleOpen(this.wzsqSqmxList)
      let obj = {};
      obj.wzxxId = "";
      obj.wzName = "";
      obj.wzDw = "";
      obj.wzGg = "";
      obj.sqSl = "";
      obj.purpose = "";
      this.wzsqSqmxList.push(obj);
    },
    /** 物资申请明细删除按钮操作 */
    handleDeleteWzsqSqmx() {
      if (this.checkedWzsqSqmx.length == 0) {
        this.$modal.msgError("请先选择要删除的物资申请明细数据");
      } else {
        const wzsqSqmxList = this.wzsqSqmxList;
        const checkedWzsqSqmx = this.checkedWzsqSqmx;
        this.wzsqSqmxList = wzsqSqmxList.filter(function (item) {
          return checkedWzsqSqmx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWzsqSqmxSelectionChange(selection) {
      this.checkedWzsqSqmx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wzgl/wzsq/export', {
        ...this.queryParams
      }, `wzsq_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
